package com.goods.business.service.imp;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.goods.business.converter.OutStockConverter;
import com.goods.business.mapper.*;
import com.goods.business.service.OutStockService;
import com.goods.common.error.BusinessCodeEnum;
import com.goods.common.error.BusinessException;
import com.goods.common.model.business.*;
import com.goods.common.response.ActiveUser;
import com.goods.common.vo.business.ConsumerVO;
import com.goods.common.vo.business.OutStockDetailVO;
import com.goods.common.vo.business.OutStockItemVO;
import com.goods.common.vo.business.OutStockVO;
import com.goods.common.vo.system.PageVO;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.UUID;

@Service
public class OutStockServiceImpl implements OutStockService {

  @Autowired
  private OutStockMapper outStockMapper;

  @Autowired
  private OutStockConverter outStockConverter;

  @Autowired
  private ConsumerMapper consumerMapper;

  @Autowired
  private OutStockInfoMapper outStockInfoMapper;

  @Autowired
  private ProductMapper productMapper;

  @Autowired
  private ProductStockMapper productStockMapper;

  /**
   * 查询所有发放记录
   * @param pageNum
   * @param pageSize
   * @param outStockVO
   * @return
   */
  @Override
  public PageVO<OutStockVO> findOutStockList(Integer pageNum, Integer pageSize, OutStockVO outStockVO) {
    PageHelper.startPage(pageNum,pageSize);
    Example o = new Example(OutStock.class);
    Example.Criteria criteria = o.createCriteria();
    o.setOrderByClause("create_time desc");
    if (outStockVO.getOutNum()!=null&&!"".equals(outStockVO.getOutNum())){
      criteria.andLike("outNum","%"+outStockVO.getOutNum()+"%");
    }
    if (outStockVO.getType()!=null){
      criteria.andEqualTo("type",outStockVO.getType());
    }
    if (outStockVO.getStatus()!=null){
      criteria.andEqualTo("status",outStockVO.getStatus());
    }
    List<OutStock> outStocks = outStockMapper.selectByExample(o);
    List<OutStockVO> outStockVOS = outStockConverter.converterToVOList(outStocks);
    PageInfo<OutStock> outStockPageInfo = new PageInfo<>(outStocks);
    return new PageVO<>(outStockPageInfo.getTotal(),outStockVOS);
  }

  /**
   * 发放明细
   * @param id
   * @param pageNum
   * @param pageSize
   * @return
   * @throws BusinessException
   */
  @Override
  public OutStockDetailVO detail(Long id, Integer pageNum, Integer pageSize) throws BusinessException {
    OutStockDetailVO outStockDetailVO = new OutStockDetailVO();
    OutStock outStock = outStockMapper.selectByPrimaryKey(id);
    if (outStock==null){
      throw new BusinessException(BusinessCodeEnum.PARAMETER_ERROR,"发放记录不存在");
    }
    BeanUtils.copyProperties(outStock,outStockDetailVO);
    Consumer consumer = consumerMapper.selectByPrimaryKey(outStock.getConsumerId());
    if (consumer==null){
      throw new BusinessException(BusinessCodeEnum.PARAMETER_ERROR,"物资领取方不存在,或已经被删除");
    }
    ConsumerVO consumerVO = new ConsumerVO();
    BeanUtils.copyProperties(consumer,consumerVO);
    outStockDetailVO.setConsumerVO(consumerVO);
    String outNum = outStock.getOutNum();
    Example o = new Example(OutStockInfo.class);
    PageHelper.startPage(pageNum,pageSize);
    o.createCriteria().andEqualTo("outNum",outNum);
    List<OutStockInfo> outStockInfoList = outStockInfoMapper.selectByExample(o);
    outStockDetailVO.setTotal(new PageInfo<>(outStockInfoList).getTotal());
    if (!CollectionUtils.isEmpty(outStockInfoList)){
      for (OutStockInfo outStockInfo : outStockInfoList) {
        String pNum = outStockInfo.getPNum();
        Example p = new Example(Product.class);
        p.createCriteria().andEqualTo("pNum",pNum);
        List<Product> products = productMapper.selectByExample(p);
        if (!CollectionUtils.isEmpty(products)){
          Product product = products.get(0);
          OutStockItemVO outStockItemVO = new OutStockItemVO();
          BeanUtils.copyProperties(product,outStockItemVO);
          outStockItemVO.setCount(outStockInfo.getProductNumber());
          outStockDetailVO.getItemVOS().add(outStockItemVO);
        }else {
          throw new BusinessException(BusinessCodeEnum.PARAMETER_ERROR,"编号为:["+pNum+"]的物资找不到,或已被删除");
        }
      }
    }else {
      throw new BusinessException(BusinessCodeEnum.PARAMETER_ERROR,"发放编号为:[\"+outNum+\"]的明细找不到,或已被删除");
    }
    return outStockDetailVO;
  }

  @Override
  public void addOutStock(OutStockVO outStockVO) throws BusinessException {
    String OUT_STOCK_NUM = UUID.randomUUID().toString().substring(0,32).replace("-","");
    int itemNumber = 0;
    List<Object> products = outStockVO.getProducts();
    if (!CollectionUtils.isEmpty(products)){
      for (Object product : products) {
        LinkedHashMap item = (LinkedHashMap) product;
        int productNumber = (int) item.get("productNumber");
        Integer productId = (Integer) item.get("productId");
        Product dbProduct = productMapper.selectByPrimaryKey(productId);
        if (dbProduct==null){
          throw new BusinessException(BusinessCodeEnum.PRODUCT_NOT_FOUND);
        }else if (productNumber<=0){
          throw new BusinessException(BusinessCodeEnum.PRODUCT_OUT_STOCK_NUMBER_ERROR,dbProduct.getName()+"发放数量不合法,无法入库");
        }else {
          Example p = new Example(ProductStock.class);
          p.createCriteria().andEqualTo("pNum",dbProduct.getPNum());
          ProductStock productStock = productStockMapper.selectOneByExample(p);
          if (productStock==null){
            throw new BusinessException(BusinessCodeEnum.PARAMETER_ERROR,"该物资在库存中不存在");
          }
          if(productNumber>productStock.getStock()){
            throw new BusinessException(BusinessCodeEnum.PRODUCT_STOCK_ERROR,dbProduct.getName()+"库存不足,库存剩余:"+productStock);
          }
          itemNumber += productNumber;
          OutStockInfo outStockInfo = new OutStockInfo();
          outStockInfo.setCreateTime(new Date());
          outStockInfo.setModifiedTime(new Date());
          outStockInfo.setProductNumber(productNumber);
          outStockInfo.setPNum(dbProduct.getPNum());
          outStockInfo.setOutNum(OUT_STOCK_NUM);
          outStockInfoMapper.insert(outStockInfo);
        }
      }
      OutStock outStock = new OutStock();
      BeanUtils.copyProperties(outStockVO,outStock);
      outStock.setCreateTime(new Date());
      outStock.setProductNumber(itemNumber);
      ActiveUser activeUser = (ActiveUser) SecurityUtils.getSubject().getPrincipal();
      outStock.setOperator(activeUser.getUser().getUsername());
      outStock.setOutNum(OUT_STOCK_NUM);
      outStock.setStatus(2);
      outStockMapper.insert(outStock);
    }else {
      throw new BusinessException(BusinessCodeEnum.PRODUCT_OUT_STOCK_EMPTY);
    }
  }
}
